class AuthenticationsController < ApplicationController

  def create
     omniauth = request.env["omniauth.auth"]
     authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
      if authentication
	   flash[:notice] = "Signed in successfully."
	   sign_in_and_redirect(:client, authentication.client)
      elsif current_client
        current_client.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
        flash[:notice] = "Authentication successful."
        redirect_to root_url
      else
        client = Client.new
        client.apply_omniauth(omniauth,true)
				if client.save(:validate => false)
          flash[:notice] = "Signed in successfully."
          sign_in_and_redirect(:client, client)

        else
         flash[:notice] = "your account not activated."
          session[:omniauth] = omniauth.except('extra')
          redirect_to new_client_registration_url
        end
      end
  end

  def destroy
    @authentication = current_client.authentications.find(params[:id])
    @authentication.destroy
    flash[:notice] = "Successfully Disconnected."
    redirect_to authentications_url
  end
	
  def failure
    flash[:alert] = "Sorry, You din't authorize"
    redirect_to authentications_url
  end

end
